package com.ywz.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.common.SymmetricAlgorithmUtils;
import com.ywz.framework.mybatisplus.MyDynamicDataSourceService;
import com.ywz.project.base.system.entity.TSysTenement;
import com.ywz.project.base.system.service.TSysTenementService;
import com.ywz.project.system.dto.req.EditTenementReq;
import com.ywz.project.system.dto.req.TenementPageReq;
import com.ywz.project.system.service.TenementApiService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TenementApiServiceImpl implements TenementApiService {
    @Resource
    private TSysTenementService TSysTenementService;
    @Resource
    private MyDynamicDataSourceService myDynamicDataSourceService;
    @Value("${tenement.datasource.username}")
    private String dbUsername;
    @Value("${tenement.datasource.password}")
    private String dbPassword;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResultResp getTenementList() {
        LambdaQueryWrapper<TSysTenement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysTenement::getIsDeleted, 0);
        queryWrapper.eq(TSysTenement::getStatus, 1);
        return ResultResp.success(TSysTenementService.list(queryWrapper));
    }

    @Override
    public ResultResp getTenementPage(TenementPageReq req) {
        LambdaQueryWrapper<TSysTenement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysTenement::getIsDeleted, 0);
        if (!StringUtils.isEmpty(req.getName()))
            queryWrapper.like(TSysTenement::getName, req.getName());
        if (!StringUtils.isEmpty(req.getSimpleName()))
            queryWrapper.eq(TSysTenement::getSimpleName, req.getSimpleName());
        if (StringUtils.isDate(req.getStartDate()))
            queryWrapper.ge(TSysTenement::getServeTime, req.getStartDate());
        if (StringUtils.isDate(req.getEndDate()))
            queryWrapper.le(TSysTenement::getServeTime, req.getEndDate());
        Page<TSysTenement> page = TSysTenementService.page(new Page<>(req.getPageNum(), req.getPageSize()), queryWrapper);
        return ResultResp.success(page);
    }


    @Override
    public ResultResp editTenement(EditTenementReq req) {
        if (StringUtils.isEmpties(req.getName(), req.getSimpleName(), req.getTenantKey(), req.getDbUrl()))
            return ResultResp.error("参数不能为空");
        if (!StringUtils.isDate(req.getServeTime()))
            return ResultResp.error("服务时间格式不正确");
        if (StringUtils.isOverLength(255, req.getName(), req.getSimpleName(), req.getTenantKey(), req.getDbUrl()))
            return ResultResp.error("参数长度超过限制");

        // 新增租户
        if (StringUtils.isNull(req.getId())) {
            // 判断租户标识是否已存在
            QueryWrapper<TSysTenement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_deleted", 0);
            queryWrapper.eq("TENANT_KEY", req.getTenantKey());
            if (TSysTenementService.count(queryWrapper) > 0)
                return ResultResp.error("租户标识已存在");
            // 添加租户信息
            TSysTenement TSysTenement = new TSysTenement();
            BeanUtils.copyProperties(req, TSysTenement);
            TSysTenement.setDbUsername(SymmetricAlgorithmUtils.encrypt(dbUsername));
            TSysTenement.setDbPassword(SymmetricAlgorithmUtils.encrypt(dbPassword));
            TSysTenement.setServeTime(LocalDateTime.parse(req.getServeTime() + "T00:00:00"));
            TSysTenement.setCreatedTime(LocalDateTime.now());
            TSysTenementService.save(TSysTenement);
            // 创建租户数据库并初始化表
            myDynamicDataSourceService.initTable(req.getTenantKey(), req.getSimpleName(), req.getDbUrl());
        } else {
            // 修改租户信息
            TSysTenement TSysTenement = new TSysTenement();
            BeanUtils.copyProperties(req, TSysTenement);
            TSysTenement.setServeTime(LocalDateTime.parse(req.getServeTime() + "T00:00:00"));
            TSysTenement.setUpdatedTime(LocalDateTime.now());
            TSysTenementService.updateById(TSysTenement);
            // 删除租户缓存
            redisTemplate.delete("tenement_" + req.getTenantKey());
        }
        return ResultResp.success();
    }

    @Override
    public ResultResp removeTenement(String ids) {
        if (!StringUtils.isNumberAndSeparator(ids))
            return ResultResp.error("参数格式不正确");
        LambdaQueryWrapper<TSysTenement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TSysTenement::getId, Arrays.asList(ids.split(StringUtils.SEPARATOR)));
        queryWrapper.eq(TSysTenement::getIsDeleted, 0);
        List<TSysTenement> list = TSysTenementService.list(queryWrapper);
        // 删除租户缓存
        List<String> collect = list.stream().map(TSysTenement -> "tenement_" + TSysTenement.getTenantKey()).collect(Collectors.toList());
        redisTemplate.delete(collect);
        // 删除租户信息
        List<TSysTenement> collect1 = list.stream().peek(TSysTenement -> {
            TSysTenement.setIsDeleted(1);
            TSysTenement.setUpdatedTime(LocalDateTime.now());
        }).collect(Collectors.toList());
        TSysTenementService.updateBatchById(collect1);
        return ResultResp.success();
    }
}
